
'''
Copyright 2010 Kensaku KOMATSU (kensaku.komatsu[at]gmail.com)

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
'''

from mod_pywebsocket import msgutil
import memcache
import thread

connections = []
#_GOODBYE_MESSAGE = 'Goodbye'

mc = memcache.Client(['127.0.0.1:11211'])
mc.set('iphone_event', '')

def checkMemcache():
    while True:
        if (len(connections) == 0):
            break
        event = mc.get('iphone_event')
        if(event != ''):
            mc.set('iphone_event', '')
            for con in connections:
                try:
                    msgutil.send_message(con, event)
                except Exception:
                    connections.remove(con)
    


def web_socket_do_extra_handshake(request):
    connections.append(request)
    pass  # Always accept.


def web_socket_transfer_data(request):
    if(len(connections) == 1):
        thread.start_new_thread(checkMemcache, ())
    
#    print len(connections)
    
    while True:
        try:
            message = msgutil.receive_message(request)
        except Exception:
            connections.remove(request)
            print len(connections)
            return

# vi:sts=4 sw=4 et
